package com.lr.server.demo1;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;

/*
 * 创建服务器并启动
 */
public class Server2 {
	
	private ServerSocket server;
	
	private static final String CRTL = "\r\n";
	
	private static final String BLANK = " ";

	public static void main(String[] args) {
		Server2 server = new Server2();
		server.start();
	}
	
	public void start(){
		try {
			server = new ServerSocket(8888);
			this.recieve();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void recieve(){
		
		try {
			Socket socket = server.accept();
			byte[] data = new byte[20400];
			int len = new DataInputStream(socket.getInputStream()).read(data);
			System.out.println(new String(data,0,len).trim());
			
			//对请求做一个响应
			
			StringBuilder responseContext = new StringBuilder();
			responseContext.append(CRTL).append("<html><p>hello word!!!</p></html>");
			
			StringBuilder response = new StringBuilder();
			//1.Htpp协议/版本   响应码  描述
			response.append("HTTP/1.1").append(BLANK).append("200").append(BLANK).append("OK");
			//2.响应头
			response.append("Accept-Ranges:bytes").append(CRTL);
			response.append("Age:12").append(CRTL);
			response.append("Cache-Control:max-age=315360000").append(CRTL);
			response.append("Connection:keep-alive").append(CRTL);
			response.append("Content-Encoding:utf-8").append(CRTL);
			response.append("Content-Length:").append(responseContext.toString().getBytes().length).append(CRTL);
			response.append("Content-Type:text/html").append(CRTL);
			response.append("Date:").append(new Date()).append(CRTL);
			response.append("Server:bfe/1.0.8.13-sslpool-patch").append(CRTL);
			response.append("Vary:Accept-Encoding,User-Agent").append(CRTL);
			//3.响应内容
			response.append(responseContext);
			
			//输出流
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			bw.write(response.toString());
			bw.flush();
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//IOUtil.IOClose(br);
		
	}
	
	public void stop(){
		
	}

}
